package com.swordxu.yim.server.msgserver;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.swordxu.yim.server.dbproxy.model.Department;
import com.swordxu.yim.server.dbproxy.model.Session;
import com.swordxu.yim.server.dbproxy.model.User;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.SelfSignedCertificate;

/**
 * Created by user063 on 2014/12/26.
 */
public final class MsgServer {
    static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));

    /**
     * 启动消息服务器
     * @throws Exception
     */
    public void start() throws Exception {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new MsgServerInitializer(sslCtx));

            b.bind("192.168.1.63",PORT).sync().channel().closeFuture().sync();


        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 连接消息服务器
     * @throws Exception
     */
    public void connect() throws Exception {
        new MsgServer().start();
    }

    public static void main(String args[]) {
        //加载数据代理插件
        C3p0Plugin c3p0Plugin = new C3p0Plugin("jdbc:mysql://192.168.59.103/db_yim?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull", "root", "abc123");
        c3p0Plugin.start();
        ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
        arp.addMapping("t_user", User.class);
        arp.addMapping("t_session", Session.class);
        arp.addMapping("t_department", Department.class);
        arp.start();
        MsgServer ls = new MsgServer();
        try {
            ls.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
